package com.lsk.admin;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.lsk.applet.AppletService;
import com.lsk.util.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 登录验证
 * Created by Administrator on 2017/12/11 0011.
 */
public class AdminService {
    Cache cache= Redis.use("ACTIVITYUSER");
    public ReturnData adminLogin(Map<String,String[] > map){
        ReturnData returnData=new ReturnData();
        String result="";
        String userCode=map.get("userCode")[0];
        String password=map.get("password")[0];
        String sql="SELECT *FROM sys_user WHERE userCode='"+userCode+"'";
        List<Record> list=Db.find(sql);
        if (list.size()>1){
            result="数据异常";
        }else if (list.size()==0){
            result="账户不存在";
        }else {
            String dbPassword=list.get(0).getStr("password");
            String ppassword= MD5.md5(userCode+list.get(0).getStr("salt")+password);
            if (ppassword.equals(dbPassword)){
                result="成功登录";
                Record userRecord = list.get(0);
                String departmentSql="";
                if (userRecord.getStr("userName").equals("超级管理员")){
                    departmentSql="SELECT *from sys_department";
                    List<Record> departmentList=Db.find(departmentSql);
                    userRecord.set("department",departmentList);
                    String permissionSql="SELECT spi.percode,spi.type, spi.url,spi.parentid,spi.id,spi.name from sys_permission spi ";//查询所拥有的权限
                    List<Record> permissionList=Db.find(permissionSql);

                    for (int i=0;i<permissionList.size();i++){
                        String url=permissionList.get(i).getStr("url");
                        int b=url.indexOf("?");
                        b=b==-1?url.length():b;
                        url=url.substring(0,b);
                        String permissionName=permissionList.get(i).getStr("name");
                        userRecord.set(url,permissionName);
                        if("0".equals(permissionList.get(i).getStr("parentid"))
                                && permissionList.get(i).getStr("parentid")!=null){
                            userRecord.set(permissionList.get(i).getStr("parentid"),permissionList.get(i));
                        }
                        System.out.println("管理员权限 ："+permissionName+"  url ："+url);
                    }

                    userRecord.set("permission", permissionList);
                    String roleSql="SELECT  sr.id,sr.name from sys_role  sr LEFT JOIN\n" +
                            "sys_user_role sur ON sr.id=sur.sys_role_id\n" +
                            "LEFT JOIN sys_user su ON su.id=sur.sys_user_id\n" +
                            "WHERE su.id='"+userRecord.getStr("id")+"'";//查询所拥有的角色SQL
                    List<Record> roleRecordList=Db.find(roleSql);//角色
                    userRecord.set("role",roleRecordList);

                }else {
                    departmentSql="SELECT\n" +
                            "\tade.id as departmentId,\n" +
                            "  ade.`name` as departmentName,\n" +
                            "  ade.parentDepartmentId\n" +
                            "FROM\n" +
                            "\tsys_department ade\n" +
                            "LEFT JOIN sys_department_user sdu ON ade.id = sdu.sys_department_id\n" +
                            "LEFT JOIN sys_user sus ON sus.id = sdu.sys_user_id\n" +
                            "WHERE\n" +
                            "\tsus.id ='"+userRecord.getStr("id")+"'";//查询所在部门sql
                    List<Record> departmentList=Db.find(departmentSql);
                    userRecord.set("department",departmentList);
                    String roleSql="SELECT sr.id,sr.name from sys_role  sr LEFT JOIN\n" +
                            "sys_user_role sur ON sr.id=sur.sys_role_id\n" +
                            "LEFT JOIN sys_user su ON su.id=sur.sys_user_id\n" +
                            "WHERE su.id='"+userRecord.getStr("id")+"'";//查询所拥有的角色SQL
                    List<Record> roleRecordList=Db.find(roleSql);//角色
                    userRecord.set("role",roleRecordList);
                    String permissionSql="SELECT  spi.percode, spi.type, spi.url, spi.parentid,spi.id,spi.name from sys_permission spi\n" +
                            "LEFT JOIN sys_user_permission sup\n" +
                            "on spi.id=sup.sys_permission_id\n" +
                            "LEFT JOIN sys_user su ON\n" +
                            "sup.sys_user_id=su.id\n" +
                            "WHERE su.id='"+list.get(0).getStr("id")+"'";//查询所拥有的权限
                    List<Record> permissionList=Db.find(permissionSql);
                    /*查询当前用户所拥有的角色携带的权限*/
                    String rolePermissionSql="SELECT spi.percode, spi.type, spi.url, spi.parentid,spi.id,spi.name from sys_permission spi LEFT JOIN sys_role_permission \n" +
                            "srp on srp.sys_permission_id=spi.id LEFT JOIN sys_user_role sur on sur.sys_role_id=srp.sys_role_id\n" +
                            "LEFT JOIN sys_user sus on sus.id=sur.sys_user_id where sus.id='"+list.get(0).getStr("id")+"'";
                    List<Record> rolePermissionList=Db.find(rolePermissionSql);
                    permissionList.addAll(rolePermissionList);
                    HashSet h = new HashSet(permissionList);
                    permissionList.clear();
                    permissionList.addAll(h);
                    for (int i=0;i<permissionList.size();i++){
                        String url=permissionList.get(i).getStr("url");
                        int a=url.indexOf("?");
                        a=a==-1?url.length():a;
                        url=url.substring(0,a);
                        String permissionName=permissionList.get(i).getStr("name");
                        userRecord.set(url,permissionName);
                        if("0".equals(permissionList.get(i).getStr("parentid"))
                                && permissionList.get(i).getStr("parentid")!=null){
                            userRecord.set(permissionList.get(i).getStr("parentid"),permissionList.get(i));
                        }
                    }
                    userRecord.set("permission", permissionList);
                }
                cache.setex(userRecord.getStr("id"),60*60,userRecord);
                Object oo=cache.get(userRecord.getStr("id"));
                returnData.setCode("000000");
                returnData.setData(AES.AESEncode(userRecord.getStr("id")));
            }else {
                result="用户或密码错误";
            }
        }
        returnData.setMsg(result);
        return returnData;
    }
    /**
     * 修改密码
     * Created by Administrator on 2017/12/11 0011.
     */
    public ReturnData updatePswd(String newPswd,String pswd ,String id) {
        ReturnData returnData = new ReturnData();
        String result = "";
        String sql="SELECT * FROM sys_user WHERE id='"+id+"'";
        List<Record> list=Db.find(sql);
        String userCode = list.get(0).getStr("userCode");//账号
        String password = list.get(0).getStr("password");//密码
      /*  String oldPasd = MD5.md5(userCode + "#" + pswd);*/
        String oldPasd= MD5.md5(userCode+list.get(0).getStr("salt")+pswd );
        Boolean aBoolean;
        if (password.equals(oldPasd)) {
            String newPasd = MD5.md5(userCode + list.get(0).getStr("salt") + newPswd);           //加载新密码
            Record record = new Record().set("id", id).set("password", newPasd);
            aBoolean = Db.update("sys_user", "id", record);
            if (aBoolean) {
                returnData.setCode("true");
                returnData.setMsg(result);
                result = "密码修改成功";
            } else {
                result = "密码修改失败!";
                returnData.setCode("false");
                returnData.setMsg(result);
            }
        } else {
            result = "原密码错误!";
            returnData.setCode("false");
        }
        returnData.setMsg(result);
        return returnData;
    }




}
